package Domain.MySqlAccessors;

import Domain.Genre;
import Domain.Exceptions.NoGenresException;
import Persistance.MySqlUtilityManagment;
import Persistance.PrintfFormat;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.StringTokenizer;
import java.util.Collection;

/**
 * Accessors to the genres table.
 * read only table.
 */
public class MySqlGenreProxy extends MySqlProxy<Genre> {

    public MySqlGenreProxy(MySqlUtilityManagment sql) {
        super(sql);
        TABLE_NAME = "genres";
        KEY_COLUMN_NAME = "id=%s";
        ALL_COLUMN_NAMES = "id, genre, description";
    }

    public Genre toRecordType(ResultSet rs) throws SQLException {
        long genreId = (Long) rs.getObject("id");
        String genre = (String) rs.getObject("genre");
        String description = (String) rs.getObject("description");
        return new Genre(genreId, genre, description);
    }

    public String toValues(Genre genre) {
        Object[] values = {String.valueOf(genre.getId()),genre.getGenre(),genre.getDescription()};
        return new PrintfFormat("%s,'%s','%s'").sprintf(values);
    }

    /**
     * this method get the ID of an actor according to his name
     * @param genre name
     * @return ID of the genre
     * @throws Domain.Exceptions.NoGenresException -movie with no genre asociated
     */
    public int getRecordByName(String genre) throws NoGenresException {
        String filter="genre=\'"+genre.trim()+"\'";
        Collection<Genre> id = searchRecords(filter);
        if( id.size()==0)
            throw new NoGenresException();
        return (int) id.iterator().next().getId();
    }
}